package com.jwpdk.util;

import java.sql.Clob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jwpdk.appframework.cache.CacheFactory;
import com.jwpdk.appframework.data.DataMap;
import com.jwpdk.appframework.data.DatasetList;
import com.jwpdk.appframework.data.IData;
import com.jwpdk.appframework.data.IDataList;
import com.jwpdk.common.Config;
import com.jwpdk.common.Constant;
import com.jwpdk.dbframework.Transaction;
import com.jwpdk.dbframework.TransactionManager;

/**
 * 字符串处理工具
 * @author 王志伟 By 2012-3-4
 */
@SuppressWarnings("unchecked")
public class StringUtils {

	public final static String	EMPTY	= "";

	/**
	 * 检查字符串是否为空或NULL。
	 * @param s 被检查的字符串
	 * @return 为空或null返回true，否则返回false。
	 */
	public static boolean IsEmptyOrNull(String s) {
		return trim(s).isEmpty();
	}

	/**
	 * 检查字符串是否为空或NULL。
	 * @param s 被检查的字符串
	 * @return 为空或null返回true，否则返回false。
	 */
	public static boolean IsEmptyOrNull(Object s) {
		return null == s || IsEmptyOrNull(s.toString());
	}

	/**
	 * 去掉前后空格避免空指针。
	 * @param s
	 * @return
	 */
	public static String trim(Object s) {
		return s == null ? "" : s.toString().trim();
	}

	/**
	 * 将一个特殊的字符串转成 字符串的数组<br>
	 * @param str : (如果字符串之间的分割符号为逗号),字符串的格式则必须为 "value,value,.....,value,";
	 * @param flag : 字符串之间的分割符号
	 * @return string[] : str 为空字符 或 NULL串返回 NULL ；
	 */

	public static String[] getArrayFromString(String str, String flag) {
		if ( str == null || str.equals("") ) {
			return null;
		}
		int i = 0;
		String tempkey;
		if ( !str.endsWith(flag) ) {
			str = str + flag;
		}
		List< String> al = new ArrayList< String>();
		i = str.indexOf(flag);
		while ( i != -1 ) {
			tempkey = str.substring(0,i);
			al.add(tempkey);
			str = str.substring(i + flag.length(),str.length());
			i = str.indexOf(flag);
		}
		String[] rs = new String[al.size()];
		return al.toArray(rs);
	}

	/**
	 * 将字符串转换成IDataList,[id=a,name=ew,value=fds],[id=b,name=ew,value=fds],[id=c,name=ew,value=fds]
	 * @param sv
	 * @return
	 */
	public static IDataList strToIDataList(String sv) {
		IDataList vl = new DatasetList();
		if ( sv == null || sv.trim().length() < 1 )
			return vl;
		String[] listv = sv.split("\\]");
		try {
			for (String s : listv) {
				String[] sl = s.split("\\[");
				if ( sl.length > 1 ) {
					String sa = sl[1];
					IData vs = new DataMap();
					for (String v : sa.split(",")) {
						vs.put(v.split("=")[0],v.split("=")[1]);
					}
					vl.add(vs);
				}
			}
			return vl;
		} catch ( Exception se ) {
			se.printStackTrace();
			return null;
		}
	}

	/**
	 * 将字符串转换成IData [id=a,name=ew,value=fds]
	 * @param sv
	 * @return
	 */
	public static IData strToIData(String sv) {
		IDataList vl = strToIDataList(sv);
		IData iData = null;
		if ( vl.size() > 0 ) {
			iData = (IData) vl.get(0);
		}
		return iData;
	}

	/**
	 * 判断字符串是否为整数
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		for (int i = str.length(); --i >= 0;) {
			if ( !Character.isDigit(str.charAt(i)) ) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 获取字符串编码
	 * @param str
	 * @return
	 */
	public static String getEncode(String str) {
		String[] encodes = { "GB2312", "ISO-8859-1", "UTF-8", "GBK" };
		for (String encode : encodes) {
			try {
				if ( str.equals(new String(str.getBytes(encode), encode)) ) {
					return encode;
				}
			} catch ( Exception exception ) {
			}
		}
		return "";
	}

	/**
	 * 获取字符串编码格式 待完善
	 * @param para
	 * @return
	 */
	@Deprecated
	public static String getEncode(String para, String defaultEncode) {
		String encode = "";
		Pattern p = Pattern.compile("^(?:[\\x00-\\x7f]|[\\xfc-\\xff]" + "[\\x80-\\xbf]{5}|[\\xf8-\\xfb][\\x80-\\xbf]{4}|" + "[\\xf0-\\xf7][\\x80-\\xbf]{3}|[\\xe0-\\xef][\\x80-\\xbf]"
				+ "{2}|[\\xc0-\\xdf][\\x80-\\xbf])+$");
		Matcher ma = p.matcher(para);
		if ( !ma.find() ) {
			encode = "gbk";
		} else {
			encode = defaultEncode;
		}
		return encode;
	}

	/**
	 * 将Clob对象转换成字符串对象
	 * @param clob
	 * @return 字符串
	 */
	public static String getStringByClob(Clob clob) {
		StringBuffer sBuffer = new StringBuffer();
		try {
			if ( clob != null ) {
				long length = clob.length();
				int c = (int) ((length - 1) / Integer.MAX_VALUE) + 1;
				for (int i = 0; i < c; i++) {
					long start = Integer.MAX_VALUE * i + 1;
					int end = (length - i * Integer.MAX_VALUE - 1) / Integer.MAX_VALUE == 0 ? (int) (length - i * Integer.MAX_VALUE) : Integer.MAX_VALUE;
					sBuffer.append(clob.getSubString(start,end));
				}
			}
		} catch ( SQLException e ) {
			e.printStackTrace();
		}
		return sBuffer.toString();

	}

	public static void main(String[] args) throws Exception {
		// String[] rs =
		/*
		 * System.out.println(StringUtils.getArrayFromString("1a,v23f,v42f,v2d1,v312f,v32a1,v23e,v4f",","));
		 * System.out.println(strToIDataList("[id=a,name=ew,value=fds],[id=b,name=ew,value=fds],[id=c,name=ew,value=fds]"));
		 * System.out.println(IsEmptyOrNull(" "));
		 */
		Config.getInstance();
		Transaction transaction = new Transaction(Constant.TAG_TRANSACTION);
		TransactionManager tManager = TransactionManager.getInstance();
		tManager.beginTransaction(transaction);
		CacheFactory.getInstance();
		tManager.endTransaction(transaction);

		Config.getInstance();
		Transaction transaction1 = new Transaction(Constant.TAG_TRANSACTION);
		TransactionManager tManager1 = TransactionManager.getInstance();
		tManager1.beginTransaction(transaction1);
		CacheFactory.getInstance();
		tManager1.endTransaction(transaction1);

	}
}
